<?php
	class Sss_Ultility_OtrsServices {

		/**
		* get soap client otrs service with username and password of the otrs service
		* 
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @return SoapClient
		*/
		public function soapClient($wsUser, $wsPass) {
			// initilize SoapClient
			$soapClient = new SoapClient(null, array('location'=> OTRS_SERVICE_URL,
			'uri'           => "Core",
			'trace'         => 1,
			'login'         => $wsUser,
			'password'      => $wsPass,
			'style'         => SOAP_RPC,
			'use'           => SOAP_ENCODED));
			return $soapClient;
		}
		/**
		* Asssign to group with userid, groupname, username and password and soapclient.
		* 
		* @param mixed $userid
		* @param mixed $groupName
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		public function assignUser2Group($userid, $userAssignId, $groupName = null, $groupId = null, $wsUser = null, $wsPass = null, $value = null){
			//Check if groupid not null when group = groupid and not get group by otrs service
			$group = null;
			if($groupId != null){
				$group = $groupId;
			}
			else{
				$group = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
				array($wsUser, $wsPass, "GroupObject", "GroupLookup",
				"Group",$groupName));
			}
			if($value == null){
				$value = 1;
			}
			//When find the group in otrs service 
			if ($group) {

				//Create array permission
				$xmlParam="<rw xsi:type='xsd:int'>$value</rw>";
				$permission = new SoapVar('<permission>'.$xmlParam.'</permission>',XSD_ANYXML);

				//Assign user to group
				$usergroup = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
				array($wsUser, $wsPass, "GroupObject","GroupMemberAdd",
				"UserID", $userid,
				"GID", $group ,
				"UID", $userAssignId,
				"Permission", $permission));

				//When assign user to group successfull
				if ($usergroup) {
					return true;
				}
				//When assign user to group fail
				else {
					return false;
				}
			}     
			//When can not find the group in the otrs service   
			else {
				return false;
			}
		}

		/**
		* Asssign to group with userid, groupname, username and password and soapclient.
		* 
		* @param mixed $userid
		* @param mixed $groupName
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		public function assignCustomer2Group($userid, $userAssignId, $groupName = null, $groupId = null, $wsUser = null, $wsPass = null){
			//Check if groupid not null when group = groupid and not get group by otrs service
			$group = null;
			if($groupId != null){
				$group = $groupId;
			}
			else{
				$group = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
				array($wsUser, $wsPass, "GroupObject", "GroupLookup",
				"Group",$groupName));
			}
			//When find the group in otrs service 
			if ($group) {

				//Create array permission
				$xmlParam='<rw xsi:type="xsd:int">1</rw>';
				$permission = new SoapVar('<permission>'.$xmlParam.'</permission>',XSD_ANYXML);

				//Assign user to group
				$usergroup = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
				array($wsUser, $wsPass, "CustomerGroupObject","GroupMemberAdd",
				"UserID", $userid,
				"GID", $group ,
				"UID", $userAssignId,
				"Permission", $permission));

				//When assign user to group successfull
				if ($usergroup) {
					return true;
				}
				//When assign user to group fail
				else {
					return false;
				}
			}     
			//When can not find the group in the otrs service   
			else {
				return false;
			}
		}
		/**
		* Create user on otrs service.
		* 
		* @param mixed $userName
		* @param mixed $passWord
		* @param mixed $role
		* @param mixed $email
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		public function createUser($userId, $validId, $arrParams) { 
			$user = $this->SoapClient($arrParams['wsuser'], $arrParams['wspass'])->__soapCall("Dispatch",
			array($arrParams['wsuser'], $arrParams['wspass'],"UserObject","UserAdd",
			"ValidID", $validId,
			"ChangeUserID", $userId,
			"UserFirstname", $arrParams['fullname'],
			"UserLastname", $arrParams['fullname'],
			"UserLogin", $arrParams['username'],
			"UserPw", $arrParams['password'],
			"UserEmail", $arrParams['email']));
			return $user;
			//Assign new user to groups
			//assignUser2Group($userId, $user, $role, $wsUser, $wsPass, $soapClient);
		}
		/**
		* Search user with username
		* 
		* @param mixed $userName
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		public function searchUser($userName, $wsUser, $wsPass, $soapClient) {
			$list = $soapClient->__soapCall("Dispatch",
			array($wsUser, $wsPass, "UserObject","UserSearch",
			"UserLogin", $userName,
			"Limit", 1
			));
			if ($list)
				return $list;
			else
				return false;
		}
		/**
		* Create customer user
		* 
		* @param mixed $userId
		* @param mixed $validId
		* @param mixed $userFirstname
		* @param mixed $userLastname
		* @param mixed $userName
		* @param mixed $passWord
		* @param mixed $email
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		function createCustomerUser($userId, $validId, $arrParams, $customerIds = null) {
			$user = $this->SoapClient($arrParams['wsuser'], $arrParams['wspass'])->__soapCall("Dispatch",
			array($arrParams['wsuser'], $arrParams['wspass'],"CustomerUserObject","CustomerUserAdd",
			"UserID", $userId,
			"ValidID",$validId,
			"Source", "CustomerUser",
			"UserFirstname", $arrParams['fullname'],
			"UserLastname",$arrParams['fullname'],
			"UserCustomerID",$arrParams['username'],
			"UserLogin", $arrParams['username'],
			"UserPassword",$arrParams['password'],
			"UserEmail",$arrParams['email'],
			"UserCustomerIDs",$customerIds));
			return $user;
		}
		/**
		* Create customer user
		* 
		* @param mixed $userId
		* @param mixed $validId
		* @param mixed $userFirstname
		* @param mixed $userLastname
		* @param mixed $userName
		* @param mixed $passWord
		* @param mixed $email
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		function updateCustomerUser($userId, $validId, $fullName = null, $userName = null, $currentUserLogin = null, $email = null, $wsUser = null, $wsPass = null, $customerIds = null) {
			$user = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
			array($wsUser, $wsPass,"CustomerUserObject","CustomerUserUpdate",
			"Source", "CustomerUser", # CustomerUser source config
			"ID", $currentUserLogin,  # current user login
			"UserLogin", $userName,
			"UserCustomerID", $currentUserLogin,   # new user login
			"UserFirstname",$fullName,
			"UserLastname",$fullName,
			"UserEmail",$email,
			"ValidID",$validId,
			"UserID",$userId,
			"UserCustomerIDs",$customerIds));
			return $user;
		}
		/**
		* Search customer user
		* 
		* @param mixed $userName
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		function searchCustomerUser($userName, $wsUser, $wsPass) {
			$list = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
			array($wsUser, $wsPass, "CustomerUserObject","CustomerSearch",
			"UserLogin",$userName,
			"Valid",1
			));
			if ($list)
				return $list;
			else
				return false;

		}
		/**
		* Auto login when login with another project
		* 
		* @param mixed $vuser
		* @param mixed $vpasswd
		* @param mixed $role
		* @param mixed $email
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $ws_url
		* @return mixed
		*/
		public function autoLogin($userId, $email = null, $vuser = null, $vpasswd = null, $role = null, $wsUser = null, $wsPass = null) {
			//Change url otrs service
			$newWsUrl = preg_replace('/rpc\.pl/','index.pl',OTRS_SERVICE_URL);
			if ($role == "Customer") {
				$newWsUrl = preg_replace('/rpc\.pl/','customer.pl',OTRS_SERVICE_URL);
			}

			$action = "Login";
			$fields = array(
			'Action' => urlencode($action),
			'User' => urlencode($vuser),
			'Password' => urlencode($vpasswd));
			$fieldsString="";
			foreach ($fields as $key=>$value) {
				$fieldsString .= $key.'='.$value.'&';
			}
			rtrim($fieldsString, '&');
			$ch = curl_init();
			$options = array(
			CURLOPT_URL=>$newWsUrl,
			CURLOPT_POST=>true,
			CURLOPT_POSTFIELDS=>$fieldsString,
			CURLOPT_COOKIESESSION=>true,
			CURLOPT_RETURNTRANSFER=>true
			);  
			curl_setopt_array($ch,$options);

			//Check role when login to otrs service
			if ($role == "BO") {
				$user = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
				array($wsUser, $wsPass, "UserObject","UserSearch",
				"UserLogin", $vuser,
				"Limit", 1
				));
				if (!$user){
					$this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
					array($wsUser, $wsPass,"UserObject","UserAdd",
					"ValidID", 1,
					"ChangeUserID", $userId,
					"UserLogin", $vuser,
					"UserPw", $vpasswd,
					"UserEmail", $email));
				}
				$result = curl_exec($ch);
				curl_close($ch);

				//Set the regex pattern to get the Session Id
				$session="";
				$pattern='/Session=([0-9a-z]+)/';
				if (preg_match($pattern,$result,$matches)) {
					$session=$matches[1];
					$newUrl= $newWsUrl."?Session=$session&Action=AgentTicketStatusView";
					return $newUrl;
				}
			}
			elseif ($role == "Customer") {
				$customerUser = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
				array($wsUser, $wsPass, "CustomerUserObject","CustomerSearch",
				"UserLogin",$vuser,
				"Valid",1
				));
				if (!$customerUser){
					$user = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
					array($wsUser, $wsPass,"CustomerUserObject","CustomerUserAdd",
					"UserID", $userId,
					"ValidID",1,
					"Source", "CustomerUser",
					"UserCustomerID",$vuser,
					"UserLogin", $vuser,
					"UserPassword",$vpasswd,
					"UserEmail",$email));
				}
				$result = curl_exec($ch);
				curl_close($ch);

				// set the regex pattern to get the Session Id
				$session="";
				$pattern='/CSID=([0-9a-z]+)/';
				if (preg_match($pattern,$result,$matches)) {
					$session=$matches[1];
					$newUrl= $newWsUrl."?CSID=$session&Action=CustomerTicketOverview;Subaction=MyTickets";
					return $newUrl;
				}
			}
			return "";
		}
		/**
		* Get list ticket
		* 
		* @param mixed $status
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		public function getTickets($status, $userId, $limit, $result, $wsUser, $wsPass, $soapClient){
			//Get list ticket ids by userid and limit
			$listTicketIds = $soapClient->__soapCall("Dispatch",
			array($wsUser, $wsPass, "TicketObject","TicketSearch",
			"Result", $result,
			"Limit", $limit,
			"UserID", $userId,
			"StateType", $status));

			//Greate list ticket and add ticket to array
			$arrListTicket = array();
			if(count($listTicketIds) > 0){
				foreach($listTicketIds as $id){
					$ticket = $soapClient->__soapCall("Dispatch",
					array($wsUser, $wsPass, "TicketObject","ArticleGet",
					"TicketID", $id,
					"Extended", 1,
					"UserID", $userId));
					$arrListTicket[] = $ticket;
				}
			}
			return $arrListTicket;
		}
		/**
		* Delete ticket
		* 
		* @param mixed $ticketId
		* @param mixed $userId
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		public function deleteTicket($ticketId, $userId, $wsUser, $wsPass, $soapClient){
			$deleteTicket = $soapClient->__soapCall("Dispatch",
			array($wsUser, $wsPass, "TicketObject","TicketDelete",
			"TicketID", $ticketId,
			"UserID", $userId));
			return $deleteTicket;
		}
		/**
		* Create group
		* 
		* @param mixed $userId
		* @param mixed $validId
		* @param mixed $name
		* @param mixed $comment
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		public function createGroup($userId, $validId, $name, $comment, $wsUser, $wsPass){
			$group = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
			array($wsUser, $wsPass,"GroupObject","GroupAdd",
			"UserID", $userId, 
			"ValidID", $validId,
			"Name", $name,
			"Comment", $comment));
			return $group;
		}
		/**
		* Assgin role to group
		* 
		* @param mixed $groupName
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		public function assignRole2Group($userId, $roleName, $groupName, $wsUser, $wsPass, $soapClient){
			//Get role by role name
			$role = $soapClient->__soapCall("Dispatch",
			array($wsUser, $wsPass, "GroupObject", "RoleLookup",
			"Group", $roleName));

			//Get group by group name
			$group = $soapClient->__soapCall("Dispatch",
			array($wsUser, $wsPass, "GroupObject", "GroupLookup",
			"Group", $groupName));

			//Create array permission
			$xmlParam ='<rw xsi:type="xsd:int">1</rw>';
			$permission = new SoapVar('<permission>'.$xmlParam.'</permission>',XSD_ANYXML);

			//Assign role to group
			$soapClient->__soapCall("Dispatch",
			array($wsUser, $wsPass, "GroupObject","GroupRoleMemberAdd",
			"UserID", $userId,
			"GID", $group ,
			"RID ", $role,
			"Permission", $permission));
		}
		/**
		* Get group by group name
		* 
		* @param mixed $groupName
		* @param mixed $wsUser
		* @param mixed $wsPass
		* @param mixed $soapClient
		*/
		public function getGroupByGroupName($groupName, $wsUser, $wsPass){
			$group = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
			array($wsUser, $wsPass, "GroupObject", "GroupLookup",
			"Group", $groupName));
			return $group;
		}

		/**
		* 
		*/
		function deleteUser($userId, $changeUserId, $valiId, $fullName, $userName, $email, $wsUser, $wsPass)
		{
			$user = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
			array($wsUser, $wsPass, "UserObject", "UserUpdate",
			"UserID", $userId,
			"ValidID", $valiId,
			"UserFirstname", $fullName,
			"UserLastname", $fullName,
			"UserLogin", $userName,
			"UserEmail", $email,
			"ChangeUserID", $changeUserId));
			return $user;
		}
		/**
		* 
		*/
		function deleteCustomer($userId, $valiId, $fullName, $userName, $email, $wsUser, $wsPass)
		{
			$user = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
			array($wsUser, $wsPass, "CustomerUserObject", "CustomerUserUpdate",
			"Source",'CustomerUser', # CustomerUser source config
			"ID", $userName,           # current user login
			"UserLogin", $userName,
			"UserCustomerID", $userName,        # new user login
			"UserFirstname", $fullName,
			"UserLastname", $fullName,
			"UserEmail", $email,
			"UserID", $userId,
			"ValidID", $valiId));
			return $user;
		}
		/**
		* 
		*/
		function updateUser($userId, $changeUserId, $valiId, $fullName, $userName, $email, $password, $wsUser, $wsPass)
		{
			$user = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
			array($wsUser, $wsPass, "UserObject", "UserUpdate",
			"UserID", $userId,
			"ValidID", $valiId,
			"UserFirstname", $fullName,
			"UserLastname", $fullName,
			"UserLogin", $userName,
			"UserPw", $password,
			"UserEmail", $email,
			"ChangeUserID", $changeUserId));
			return $user;
		}

		public function addQueue($userId, $validId, $title, $group, $wsUser, $wsPass) { 
			$queue = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
			array($wsUser, $wsPass,"QueueObject","QueueAdd",
			"Name", $title,
			"ValidID", $validId,
			"GroupID", $group,
			"SystemAddressID", 1,
			"SalutationID", 1,
			"SignatureID", 1,
			"UserID", $userId));
			return $queue;
			//Assign new user to groups
			//assignUser2Group($userId, $user, $role, $wsUser, $wsPass, $soapClient);
		}
		/**
		* 
		*/
		function updateCustomer($userName, $password, $wsUser, $wsPass)
		{
			$user = $this->SoapClient($wsUser, $wsPass)->__soapCall("Dispatch",
			array($wsUser, $wsPass, "CustomerUserObject", "SetPassword",
			"UserLogin", $userName,       # new user login
			"PW", $password));
			return $user;
		}
		function checka($wsUser, $wsPass){
			return $this->SoapClient($wsUser, $wsPass);
		}
	}
